<?php
class MailSmtp extends AbsMail {
	/**
	 * 发送邮件主函数
	 */
	public static function mail() {
		$configs = Mail::$cfg;
		$mailer = self::getMailer();
		$mailer->ClearAddresses(); //如果在循环中调用该函数，必须清空之前的收件人列表
		$mailer->ClearAttachments();
		$mailer->ClearBCCs();
		$mailer->ClearCCs();
		$mailer->IsHTML($configs['html']); //设置是否是html
		$mailer->Subject = $configs['subject']; //设置主题
		$mailer->Body = $configs['body']; //设置主体
		$mailer->Priority = $configs['priority']; //设置优先级
		$mailer->Encoding = $configs['encoding']; //设置邮件编码
		$mailer->LE = $configs['le']; //设置换行符
		if(is_array($configs['to'])) {
			foreach($configs['to'] as $to) {
				$mailer->AddAddress($to);
			}
		} else {
			$mailer->AddAddress($configs['to']); //添加目的地
		}
		//添加附件
		foreach($configs['attachments'] as $attachment) {
			$mailer->AddAttachment($attachment);
		}
		//添加bcc（在邮件中看不到）
		foreach($configs['bcc'] as $bcc) {
			$mailer->AddBCC($bcc);
		}
		//添加cc（可以在邮件中看到）
		foreach($configs['cc'] as $cc) {
			$mailer->AddCC($cc);
		}
		return $mailer->Send(); //发送
	}
	
	/**
	 * 获取phpmailer
	 */
	private static function getMailer() {
		static $mailers;
		$configs = Mail::$cfg;
		$guid = md5($configs['charset'] . $configs['smtp_ssl'] . $configs['smtp_auth'] . $configs['smtp_user'] . $configs['smtp_pwd'] . $configs['smtp_host'] . $configs['smtp_port'] . $configs['from'] . $configs['sender'] . $configs['fromname'] . $configs['altbody'] . $configs['smtp_keepalive'] . $configs['smtp_timeout'] . $configs['smtp_debug']);
		
		if(!isset($mailers[$guid])) {
			$mailer = new PHPMailer();
			$mailer->IsSMTP();
			$mailer->SetFrom($configs['from'], $configs['fromname']);
			$mailer->CharSet = $configs['charset'];
			if($configs['smtp_ssl']) {
				$mailer->SMTPSecure = 'ssl';
			}
			if($configs['smtp_auth']) {
				$mailer->SMTPAuth = true; //打开验证就能发送邮件
				$mailer->Username = $configs['smtp_user'];
				$mailer->Password = $configs['smtp_pwd'];
			}
			$mailer->Host = $configs['smtp_host'];
			$mailer->Port = $configs['smtp_port'];
			$mailer->Sender = $configs['sender'];
			$mailer->AltBody = $configs['altbody'];
			$mailer->SMTPKeepAlive = $configs['smtp_keepalive'];
			$mailer->Timeout = $configs['smtp_timeout'];
			$mailer->SMTPDebug = $configs['smtp_debug'];
			$mailers[$guid] = $mailer;
		}
		
		return $mailers[$guid];
	}
}
?>